package com.y.ari.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.y.ari.common.AriException;
import com.y.ari.common.RestResponse;
import com.y.ari.common.UserHolder;
import com.y.ari.dto.OrdersFormDTO;
import com.y.ari.dto.OrdersSelDTO;
import com.y.ari.dto.PageDTO;
import com.y.ari.entity.*;
import com.y.ari.mapper.OrdersContactsMapper;
import com.y.ari.mapper.OrdersMapper;
import com.y.ari.mapper.OrdersPaxMapper;
import com.y.ari.mapper.SeatMapper;
import com.y.ari.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 订单信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersContactsMapper ordersContactsMapper;

    @Autowired
    private SeatMapper seatMapper;

    @Autowired
    private OrdersPaxMapper ordersPaxMapper;


    @Transactional
    @Override
    public RestResponse addOrder(OrdersFormDTO ordersFormDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersFormDTO, orders);
        //插入订单表
        String s = UUID.randomUUID().toString();
        orders.setOrderNo(s);
        orders.setOrderTime(LocalDateTime.now());
        Long userId = UserHolder.getUser().getId();
        orders.setUserId(userId);
        orders.setStatus(1);

        int insert = ordersMapper.insert(orders);
        if (insert == 0) {
            AriException.cast("插入失败");
        }
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getOrderNo, s).eq(Orders::getUserId, userId);

        Orders selectOne = ordersMapper.selectOne(queryWrapper);

        //插入订单联系人信息
        OrdersContacts ordersContacts = new OrdersContacts();
        BeanUtils.copyProperties(ordersFormDTO.getContact(), ordersContacts);

        //获取插入id和订单id
        long currentTime = System.currentTimeMillis();
        ordersContacts.setId(currentTime);
        ordersContacts.setOrderId(selectOne.getId());

        int insert1 = ordersContactsMapper.insert(ordersContacts);
        if (insert1 == 0) {
            AriException.cast("插入失败");
        }

        List<OrdersPax> passengers = ordersFormDTO.getPassengers();
        for (int i = 0; i < passengers.size(); i++) {
            OrdersPax ordersPax = passengers.get(i);
            ordersPax.setOrderContactsId(currentTime);
            ordersPax.setOrderId(selectOne.getId());
        }
        int i = ordersPaxMapper.batchInsert(passengers);
        if (i == 0) {
            AriException.cast("插入失败");
        }
        return RestResponse.success(selectOne.getId(), "订票成功");
    }

    @Transactional
    @Override
    public RestResponse payOrder(Long id) {

        Orders orders = ordersMapper.selectById(id);

        LambdaQueryWrapper<OrdersPax> queryWrapperOrderPax = new LambdaQueryWrapper<>();
        queryWrapperOrderPax.eq(OrdersPax::getOrderId, id);

        //给乘机人分配座位
        List<OrdersPax> ordersPaxList = ordersPaxMapper.selectList(queryWrapperOrderPax);

        LambdaQueryWrapper<Seat> queryWrapperSeat = new LambdaQueryWrapper<>();
        queryWrapperSeat.eq(Seat::getIsAnyone, 0).eq(Seat::getCabinsId, orders.getCabinId());
        List<Seat> seatsList = seatMapper.selectList(queryWrapperSeat);

        Integer buyNumber = orders.getBuyNumber();
        if (seatsList.size() < buyNumber) {
            AriException.cast("机票数量不足！");
        }

        // 插入订单乘机人：座位id
        for (int i = 0; i < buyNumber; i++) {
            OrdersPax ordersPax = ordersPaxList.get(i);
            ordersPax.setSeatId(seatsList.get(i).getId());
            Seat seat = new Seat();
            seat.setId(seatsList.get(i).getId());
            seat.setIsAnyone(1);
            int seatI = seatMapper.updateById(seat);
            if (seatI == 0) {
                AriException.cast("机票数量不足！");
            }
            int opmI = ordersPaxMapper.updateById(ordersPax);
            if (opmI == 0) {
                AriException.cast("机票数量不足！");
            }
        }

        orders.setStatus(2);
        int ordersI = ordersMapper.updateById(orders);
        if (ordersI == 0) {
            AriException.cast("机票数量不足！");
        }
        return RestResponse.success("支付成功");
    }

    /**
     * 单个用户订单查询
     *
     * @return
     */
    @Transactional
    @Override
    public List<OrdersSelDTO> selOrders() {
        Long userId = UserHolder.getUser().getId();
        List<OrdersSelDTO> ordersSelDTOList = ordersMapper.selOrders(userId);
        return ordersSelDTOList;
    }

    /**
     * 管理端订单查询
     *
     * @return
     */
    @Transactional
    @Override
    public PageDTO selOrdersM(PageParams pageParams) {
        Long offset = (pageParams.getPageNo() - 1) * pageParams.getPageSize();
        List<OrdersSelDTO> ordersSelDTOList = ordersMapper.selOrdersM(offset, pageParams.getPageSize());

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        Integer integer = ordersMapper.selectCount(queryWrapper);

        PageDTO pageDTO = new PageDTO(ordersSelDTOList, integer, pageParams.getPageNo(), pageParams.getPageSize());
        return pageDTO;
    }

    @Transactional
    @Override
    public RestResponse mOrder(Long id) {
        Orders ordersI = ordersMapper.selectById(id);
        if (ordersI == null) {
            AriException.cast("订单不存在");
        }
        //修改订单状态
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(4);
        int oi = ordersMapper.updateById(orders);
        if (oi == 0) {
            AriException.cast("订单不存在");
        }
        //退订
        if (ordersI.getStatus() == 1) {
            List<OrdersSelDTO> ordersSelDTOList = ordersMapper.selOrders(ordersI.getUserId());
            return RestResponse.success(ordersSelDTOList, "退订成功");
        }

        //取消订单
        LambdaQueryWrapper<OrdersPax> queryWrapperPax = new LambdaQueryWrapper<>();
        queryWrapperPax.eq(OrdersPax::getOrderId, id);
        List<OrdersPax> ordersPaxList = ordersPaxMapper.selectList(queryWrapperPax);
        if (ordersPaxList == null) {
            AriException.cast("订单异常");
        }

//        座位设为没人，收回分配给乘机人的座位
        for (int i = 0; i < ordersPaxList.size(); i++) {
            Seat seat = new Seat();
            seat.setId(ordersPaxList.get(i).getSeatId());
            seat.setIsAnyone(0);
            int si = seatMapper.updateById(seat);
            OrdersPax ordersPax = new OrdersPax();
            ordersPax.setId(ordersPaxList.get(i).getId());
            ordersPax.setSeatId(ordersPaxList.get(i).getSeatId());
            int op = ordersPaxMapper.updateById(ordersPax);
            if (op == 0 || si == 0) {
                AriException.cast("订单异常");
            }
        }

        List<OrdersSelDTO> ordersSelDTOList = ordersMapper.selOrders(ordersI.getUserId());
        return RestResponse.success(ordersSelDTOList, "取消订单成功");
    }

    @Transactional
    @Override
    public RestResponse delOrder(Long id) {
        Orders ordersI = ordersMapper.selectById(id);
        if (ordersI == null) {
            AriException.cast("订单不存在");
        }
        LambdaQueryWrapper<OrdersPax> queryWrapperPax = new LambdaQueryWrapper<>();
        queryWrapperPax.eq(OrdersPax::getOrderId, id);
        int dp = ordersPaxMapper.delete(queryWrapperPax);
        if (dp == 0) {
            AriException.cast("删除失败");
        }

        LambdaQueryWrapper<OrdersContacts> queryWrapperC = new LambdaQueryWrapper<>();
        queryWrapperC.eq(OrdersContacts::getOrderId, id);
        int dc = ordersContactsMapper.delete(queryWrapperC);
        if (dc == 0) {
            AriException.cast("删除失败");
        }

        int dO = ordersMapper.deleteById(id);
        if (dO == 0) {
            AriException.cast("删除失败");
        }

        List<OrdersSelDTO> ordersSelDTOList = ordersMapper.selOrders(ordersI.getUserId());
        return RestResponse.success(ordersSelDTOList, "删除订单成功");
    }


}
